package com.pig4cloud.pigx.common.security.component.exceptionProcessed;


import cn.hutool.http.HttpStatus;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pig4cloud.pigx.common.security.constant.CommonConstants;
import com.pig4cloud.pigx.common.security.util.PigxSecurityMessageSourceUtil;
import com.pig4cloud.pigx.common.security.util.R;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @description: 异常处理 {@link AuthenticationException } 不同细化异常处理
 * @Author 兔子不吃窝边曹
 * @create 2022/8/8 9:14
 **/
@Slf4j
@Component
@AllArgsConstructor
public class PigxCommenceAuthExceptionEntryPoint implements AuthenticationEntryPoint {

    private final ObjectMapper objectMapper;

    @Override
    @SneakyThrows
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) {
        response.setCharacterEncoding(CommonConstants.UTF8);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
        R<String> result = new R<>();
        result.setMsg(authException.getMessage());
        result.setData(authException.getMessage());
        result.setCode(CommonConstants.FAIL);

        // 用户凭证已过期
        if (authException instanceof CredentialsExpiredException
                || authException instanceof InsufficientAuthenticationException) {
            String msg = PigxSecurityMessageSourceUtil.getAccessor().getMessage(
                    "AbstractUserDetailsAuthenticationProvider.credentialsExpired", authException.getMessage());
            result.setMsg(msg);
        }

        // 未绑定登录账号，请使用密码登录后绑定
        if (authException instanceof UsernameNotFoundException) {
            String msg = PigxSecurityMessageSourceUtil.getAccessor().getMessage(
                    "AbstractUserDetailsAuthenticationProvider.noopBindAccount", authException.getMessage());
            result.setMsg(msg);
        }

        // 客户端信息错误，Basic认证失败
        if (authException instanceof BadCredentialsException) {
            String msg = PigxSecurityMessageSourceUtil.getAccessor().getMessage(
                    "AbstractUserDetailsAuthenticationProvider.badClientCredentials", authException.getMessage());
            result.setMsg(msg);
        }

        // token 过期
        // 401 用于登录过程中的异常  424 check_token 过程中的异常
        if (authException instanceof InsufficientAuthenticationException) {
            String msg = PigxSecurityMessageSourceUtil.getAccessor().getMessage(
                    "AbstractUserDetailsAuthenticationProvider.credentialsExpired", authException.getMessage());
            response.setStatus(org.springframework.http.HttpStatus.FAILED_DEPENDENCY.value());
            result.setMsg(msg);
        }

        PrintWriter printWriter = response.getWriter();
        printWriter.append(objectMapper.writeValueAsString(result));
    }

}
